<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('流程标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('流程标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <tree-select
              v-model="form.deptId"
              :default-expand-all="true"
              :data="initData.deptOptions"
              :placeholder="$t('请选择')"
              node-key="id"
              clearable
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applicationTime">
            <el-date-picker
              v-model="form.applicationTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出门时间')" prop="goOutTime">
            <el-date-picker
              v-model="form.goOutTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('出门时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('物资去向')" prop="whereaboutsOfMaterials">
            <el-input v-model="form.whereaboutsOfMaterials" type="textarea" :placeholder="$t('物资去向')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('物资用途')" prop="useOfMaterials">
            <el-input v-model="form.useOfMaterials" type="textarea" :placeholder="$t('物资用途')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--      明细-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('物资明细') }}</span>
      </div>
      <el-table :data="form.oaMaterialDetails" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('物资明细')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('物资名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaMaterialDetails.' + scope.$index + '.materialName'" :rules="oaMaterialDetailsCheck.materialName">
              <el-input v-model="scope.row.materialName" :placeholder="$t('物资名称')" show-word-limit maxlength="300" />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column :label="$t('规格')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('规格') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaMaterialDetails.' + scope.$index + '.specifications'" :rules="oaMaterialDetailsCheck.specifications">
              <el-input v-model="scope.row.specifications" :placeholder="$t('数量/单位')" show-word-limit maxlength="300" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'oaMaterialDetails.' + scope.$index + '.remark'" :rules="oaMaterialDetailsCheck.remark">
              <el-input
                v-model="scope.row.remark"
                :placeholder="$t('备注')"
                type="textarea"
                maxlength="2000"
                :autosize="{ minRows: 1, maxRows: 10}"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="delRow(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRow">{{ $t('添加') }}</el-button>
      </div>

      <!--文件-->
      <FileTable :list.sync="form.fileList" :data-type="dataType" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:material" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
import { saveOaMaterial, getOaMaterial } from '@/api/oa/daily/material/oaMaterial'
import TreeSelect from '@/components/TreeSelect'
import { treeselect } from '@/api/system/dept'
import { getUser } from '@/api/system/user'
import { delOaMaterialDetails } from '@/api/oa/daily/material/OaMaterialDetails'
export default {
  components: { TreeSelect },
  data() {
    return {
      // 菜单标识
      menuKey: this.$t('oa_material'),
      otherBtnHide: false,
      dataType: 'oa_material',
      // 表单参数
      form: {
        oaMaterialDetails: [],
        fileList: []
      },
      // 表单校验
      rules: {
        actTitle: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], userId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], deptId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], applicationTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], goOutTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], materialDetails: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], whereaboutsOfMaterials: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], useOfMaterials: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ] },
      oaMaterialDetailsCheck: {
        materialName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        specifications: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      initData: {
        deptOptions: []
      }
    }
  },
  created() {
    this.initDataMethod()
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getOaMaterial(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        userId: this.$store.state.user.userId,
        deptId: undefined,
        applicationTime: new Date(),
        goOutTime: undefined,
        materialDetails: undefined,
        whereaboutsOfMaterials: undefined,
        useOfMaterials: undefined,
        oaMaterialDetails: [],
        fileList: []
      }
      this.resetForm('form')
      // 根据当前用户回显部门
      getUser(this.$store.state.user.userId).then(res => {
        this.$set(this.form, 'deptId', res.data.deptId)
      })
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveOaMaterial(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 启动流程
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                reject()
                this.msgError(response.msg)
                this.loading = false
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = this.$t('oa_material')
      // 业务ID
      processData.dataId = dataId.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/daily/material/oaMaterialForm'
      processData.viewPath = '@/views/oa/daily/material/oaMaterialView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    initDataMethod() {
      // 部门数据
      treeselect().then(response => {
        this.initData.deptOptions = response.data
      })
    },
    // 删除物资明细
    delRow(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return delOaMaterialDetails(id)
        }).then(() => {
          this.form.oaMaterialDetails.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
      } else {
        this.form.oaMaterialDetails.splice(index, 1)
      }
    },
    // 添加物资明细
    addRow() {
      const row = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        materialId: undefined,
        materialName: undefined,
        specifications: undefined,
        remark: undefined
      }
      this.form.oaMaterialDetails.push(row)
    }

  }

}
</script>
